﻿using DotNetCommon.Data;
using DotNetCommon.Validate;
using NUnit.Framework;
using Shouldly;
using System;

namespace DotNetCommon.Test.Validate
{
    internal class SimpleDesignDemo
    {
        #region model
        public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int? Age { get; set; }
            public DateTime? Birth { get; set; }
            public string IdCard { get; set; }
            public string Addr { get; set; }
            public string Phone { get; set; }
            public string Email { get; set; }

            /// <summary>
            /// 校验新增Student
            /// </summary>
            /// <param name="ctx"></param>
            public static void ValidAdd(IValidateContext<Student> ctx)
            {
                ctx.MustNotNull().IfFailThenExit();
                ctx.RuleFor(i => i.Id).MustBe(0);
                ctx.RuleFor(i => i.Name).MustNotNullOrWhiteSpace().MustLengthInRange(1, 4);
                ctx.RuleFor(i => i.Age).When(i => i != null, c => c.MustGreaterThanOrEuqalTo(0));
                ctx.RuleFor(i => i.Birth).When(i => i != null, c => c.MustGreaterThanOrEuqalTo(DateTime.Parse("1800-01-01")));
                ctx.RuleForIfNotNull(i => i.IdCard, ctx => ctx.MustIdCard());
                ctx.RuleForIfNotNull(i => i.Phone, ctx => ctx.When(i => i != null, c => c.MustCellPhone()));
                ctx.RuleForIfNotNull(i => i.Email, ctx => ctx.When(i => i != null, c => c.MustEmailAddress()));
            }
        }
        #endregion

        public Result<bool> AddStudent(Student student)
        {
            var res = VValid.ValidResult(student, Student.ValidAdd);
            if (!res.Success) return res;
            //...新增操作
            return Result.Ok(true);
        }

        [Test]
        public void Test()
        {
            var student = new Student()
            {
                Id = 5,
                Age = -18,
                Birth = DateTime.Parse("1220-01-01"),
                Email = "sdhiahsd.com",
                IdCard = "415551515",
                Phone = "4521"
            };
            var res = AddStudent(student);
            res.Success.ShouldBeFalse();
            res.Message.ShouldNotBeNullOrWhiteSpace();
        }
    }
}
